package com.gdcp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gdcp.beans.News;
import com.gdcp.beans.Product;
import com.gdcp.beans.Shop;
import com.gdcp.beans.User;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.annotation.RedisCache;
import com.gdcp.mapper.NewsMapper;
import com.gdcp.service.NewsService;
import com.gdcp.util.FileUtil;
import com.gdcp.util.ImageDto;
import com.gdcp.util.ImageUtil;
import com.gdcp.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Service
public class NewsServiceImpl implements NewsService {

    @Autowired
    private ResponseModel responseModel;
    @Autowired
    NewsMapper newsMapper;

    @Override
    public Map<String, Object> findPageBreakByCondition(Map<String, Object> model) {
        //bootstrap-table要求服务器返回的json须包含：totlal，rows
        Map<String,Object> result = new HashMap<>();
        int total=newsMapper.findPageBreakByCondition(null).size();
        List<News> rows=newsMapper.findPageBreakByCondition(model);
        if (rows.size()==0){
            int count= (int) model.get("a");
            count=count-(int) model.get("b");
            if (count>=0) {
                model.put("a", count);
                rows = newsMapper.findPageBreakByCondition(model);
            }
        }
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    public Map<String,Object> insert(News news, ImageDto coverImage) {
        return insertImage("insert",news,coverImage);
    }

    @Override
    public Map<String,Object> updateInformation(News news, ImageDto coverImage) {
        return insertImage("edit",news,coverImage);
    }

    @Override
    public Map<String, Object> insert(News news) {
        int count=newsMapper.insert(news);
        if (count > 0){
            return responseModel.setModel(true,"添加成功");
        }

        return responseModel.setModel(false,"添加失败");
    }

    @Override
    public Map<String, Object> updateInformation(News news) {
        int count=newsMapper.updateByPrimaryKey(news);
        if (count > 0){
            return responseModel.setModel(true,"修改成功");
        }

        return responseModel.setModel(false,"修改失败");
    }

    @Override
    public News getInformation(Integer id) {
        return newsMapper.getInformation(id);
    }

    @Override
    @Transactional(rollbackFor = { Exception.class })
    public Map<String, Object> removeByPrimaryKey(Integer[] ids) {
        try{
            for (Integer id:ids){
                newsMapper.removeByPrimaryKey(id);
                News news=this.getInformation(id);
                FileUtil.deleteFile(news.getContent_url());
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseModel.setModel(false,"删除["+ids.length+"条记录失败"+e.toString());
        }
        return responseModel.setModel(true,"成功删除["+ids.length+"条记录");
    }

    @Override
    public Map<String, Object> searchInformation(Map<String, Object> model) {
        Map<String,Object> result = new HashMap<>();
        int total=newsMapper.searchInformation(null).size();
        List<Shop> rows=newsMapper.searchInformation(model);
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    @RedisCache(flush = true)
    public List<News> queryByLimit() {
        return newsMapper.queryByLimit();
    }

    @Override
    public void updateLooks(Integer news_id) {
        newsMapper.updateLooks(news_id);
    }


    private Map<String,Object> insertImage(String str, News news, ImageDto coverImage){
        boolean str_boolean=str.equals("edit");
        Integer url=100;
        if (coverImage!=null){
            if (str_boolean){
                url=news.getId();
            }
            String dest= PathUtil.getShopImagePath(url);

            try {
                String imageAddr = ImageUtil.generateThumbnail(coverImage, dest);
                news.setCover_image(imageAddr);
            } catch (UnsupportedEncodingException e) {
                return responseModel.setModel(false,e.toString());
            }
        }

        int count;

        if (str_boolean){
            count=newsMapper.updateByPrimaryKey(news);
            if (count > 0){
                return responseModel.setModel(true,"修改成功");
            }

            return responseModel.setModel(false,"修改失败");
        }

        count=newsMapper.insert(news);
        if (count > 0){
            return responseModel.setModel(true,"添加成功");
        }

        return responseModel.setModel(false,"添加失败");
    }
}
